#!/usr/bin/python3

import requests
import os
from sys import stdout
import time


def download_file(down_url, file_path):
    """下载文件并显示过程
    :param down_url: 资源地址
    :param file_path: 保存的文件路径
    """

    with open(file_path, "wb") as fw:
        with requests.get(down_url, stream=True) as r:
            # 此时只有响应头被下载
            # print(r.headers)
            print("下载文件基本信息:")
            print('-' * 30)
            s = file_path.split("/")
            filename = s[len(s) - 1]
            print("文件名称:", filename)
            print("文件类型:", r.headers["Content-Type"])
            file_size = r.headers["Content-Length"]
            print("文件大小:", file_size, "bytes")
            print("下载地址:", down_url)
            print("保存路径:", file_path)
            print('-' * 30)
            print("开始下载")

            chunk_size = 128
            times = int(file_size) // chunk_size
            show = 1 / times
            show2 = 1 / times
            start = 1
            for chunk in r.iter_content(chunk_size):
                fw.write(chunk)
                if start <= times:
                    stdout.write(f"下载进度: {show:.2%}\r")
                    start += 1
                    show += show2
                else:
                    stdout.write("下载进度: 100%")
            print("\n结束下载")


def my_download(down_url, file_path):
    """下载文件并显示过程
        :param down_url: 资源地址
        :param file_path: 保存的文件路径
        """
    t1 = time.time()
    with open(file_path, 'wb') as f:
        down_data_count = 0
        speed_count = 0
        chunk_size = 128
        m = 1024 * 1024
        k = 1024
        with requests.get(down_url, stream=True) as r:
            for chunk in r.iter_content(chunk_size):
                data_length = len(chunk)
                down_data_count += data_length
                speed_count += data_length
                f.write(chunk)
                size_str = str(down_data_count)
                if down_data_count > m:
                    size_str = str(down_data_count/m) + "M"
                elif down_data_count > k:
                    size_str = str(down_data_count / k) + "K"

                t2 = time.time()
                if t2 - t1 > 1:
                    size_str = str(down_data_count)
                    if down_data_count > m:
                        size_str = str(down_data_count/m) + "M"
                    elif down_data_count > k:
                        size_str = str(down_data_count / k) + "K"
                    
                    speed_str = str(speed_count)
                    if speed_count > m:
                        speed_str = str(speed_count/m) + "M"
                    elif speed_count > k:
                        speed_str = str(speed_count / k) + "K"
                    print("                                     \t\t", end='\r')
                    print(size_str + "\t" + speed_str, end='\r')
                    t1 = t2
                    speed_count = 0


novelId = input("请输入小说ID:")
url = "https://zjl.hmxingkong.com/n/novel/voiceList/" + novelId
resp = requests.get(url)
# print(resp.text)
itemJsonArray = resp.json()
novelName = ""
if len(itemJsonArray) > 0:
    print(itemJsonArray[0]["artist"])
    novelName = itemJsonArray[0]["artist"]

i = 0
for item in itemJsonArray:
    itemName = item['musicName']
    i += 1
    print(str(i) + ":\t" + itemName)

startIdx = input("请输入开始序号(包含)：")
endIdx = input("请输入结束序号(包含)：")

# 获取开始到结束index列表，因为列表是从0开始,所以要减1, 而range结束参数是不包含的
indexList = list(range(int(startIdx) - 1, int(endIdx)))
# print("要下载的章节：
defaultDir = "/home/long655113/下载"
baseDir = input("请输入小说下载目录(不包含小说名),直接回车选择默认目录(" + defaultDir + "):")
if len(baseDir) == 0:
    baseDir = defaultDir
# print(baseDir)
fileDir = baseDir + "/" + novelName
print("下载文件：")
if os.path.exists(fileDir) is False:
    os.makedirs(fileDir)
for idx in indexList:
    print(itemJsonArray[idx]['musicName'] + "\t" + itemJsonArray[idx]['musicURL'])
    downUrl = itemJsonArray[idx]['musicURL']
    fileName = itemJsonArray[idx]['musicName'] + ".mp3"
    s = downUrl.split("/")
    fileName = s[len(s) - 1] + fileName
    filePath = fileDir + "/" + fileName
    try:

        # resp = requests.get(downUrl)
        # with open(filePath, 'wb') as f:
        #     f.write(resp.content)
        my_download(downUrl, filePath)

    except:
        print("request error url:" + downUrl)
